package kz.pdt12.hw.framework;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;

import java.util.NoSuchElementException;

/**
 * Created with IntelliJ IDEA.
 * User: raimbek
 * Date: 09.03.13
 * Time: 1:02
 */
public abstract class WebDriverHelperBase extends HelperBase {
    protected WebDriver driver;

    public WebDriverHelperBase(ApplicationManager manager) {
        super(manager);
        this.driver = manager.getDriver();
    }

    public void type(By locator, String text) {
        if (text != null) {
            WebElement element = driver.findElement(locator);
            element.clear();
            element.sendKeys(text);
        }
    }

    public String getTextElement(By locator) {
        WebElement element = driver.findElement(locator);
        if (element.getTagName().equals("input")) {
            return element.getAttribute("value");
        }
        return element.getText();
    }

    public String getSelectedValue(By locator) {
        WebElement element = driver.findElement(locator);
        return new Select(element).getFirstSelectedOption().getText();
    }

    public void selectByVisibleText(By locator, String text) {
        if (text != null) {
            new Select(driver.findElement(locator)).selectByVisibleText(text);
        }
    }

    public void click(By locator) {
        driver.findElement(locator).click();
    }

    public boolean isElementPresent(By by) {
        try {
            driver.findElement(by);
            return true;
        } catch (NoSuchElementException e) {
            return false;
        }
    }

    public boolean isElementPresent(WebElement element, By by) {
        try {
            element.findElement(by);
            return true;
        } catch (NoSuchElementException e) {
            return false;
        }
    }
}
